// 题目类型map.
var typeMap = new Map();
var typeList = null;
// 题目等级map.
var gradeMap = new Map();
var gradeList = null;
$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'exam/paperDesign/list',
        datatype: "json",
        colModel: [			
			/*{ label: '隶属专业', name: 'majorName', index: 'name', width: 80 },
			{ label: '章节', name: 'sectionName', index: 'name', width: 80 },*/
			{ label: '试卷名称', name: 'name', index: 'name', width: 80 },
			{ label: '试卷数量', name: 'produceQuantity', index: 'name', width: 80 },
			{ label: '题目总数', name: 'questionQuantity', index: 'name', width: 80 },
			{ label: '试卷总分', name: 'totalScore', index: 'name', width: 80 },
			{ label: '使用状态', name: 'status', index: 'name', width: 80 ,formatter:function(value,options,row) {
			    if (value == 0) {
			        return "未使用";
			    } else if (value == 1) {
			        return "已使用";
			    }
			}},
			{ label: '创建时间', name: 'createTime', index: 'createTime', width: 80, formatter:function(value,options,row){
                return new Date(value).Format('yyyy-MM-dd HH:mm:ss');}}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        multiboxonly: true, // 单选.
        beforeSelectRow: beforeSelectRow, // 单选控制  触发下面定义的单选方法.
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        	// 隐藏全选.
            $("#jqgh_jqGrid_cb").hide();
        }
    });
    // 单选控制.
    function beforeSelectRow() {
        $("#jqGrid").jqGrid('resetSelection');
        return(true);
    }

    //执行一个laydate实例
    laydate.render({
  	  elem: '#workDate',
  	  istime: true,
  	  choose: function(dates){ // 选择日期完毕的回调
  	  _this.start_time=dates;
  	  }
    });
    
    
    // 试卷查看列表.
    $("#paperJqGrid").jqGrid({
        url: baseURL + '/exam/paperProduce/getPaperList',
        datatype: "json",
        colModel: [         
            { label: '<div>试卷名称</div>', name: 'paperName', index: 'name', width: 80 },
            {
                label: '操作', name: 'flag', index: 'flag', width: 80, align: 'center',
                formatter: function (cellvalue, options, rowObject) {
                    var html = 
                            "<a class='btn btn-primary' onclick='seePaper(" + rowObject.id +", \"" + rowObject.paperName + "\")'/ value='查看'><span class='glyphicon glyphicon-book'></span>&nbsp;查看</a>"
                        + "  <a class='btn btn-primary' onclick='downLoadPaper(" + rowObject.id +", \"" + rowObject.paperName + "\")'/ value='下载pdf'><span class='glyphicon glyphicon-download-alt'></span>&nbsp;下载pdf</a>";
                    return html;
                },
            }
        ],
        viewrecords: true,
        width: 500,
        height: 500,
        jsonReader : {
            root: "paperList"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#paperJqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    
    
    $(".selectpicker").selectpicker({  
        noneSelectedText : '请选择'  ,
        liveSearchPlaceholder : "请输入关键字",
        noneResultsText : "内容无法匹配"
    });
});

var setting = {
	    data: {
	        simpleData: {
	            enable: true,
	            idKey: "deptId",
	            pIdKey: "parentId",
	            rootPId: -1
	        },
	        key: {
	            url:"nourl"
	        }
	    }
	};

var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
            username: null
        },
		showList: true,
		title: null,
		addShow:true,
		majorList :{},
		sectionList :{},
		paperDesign: {deptName:null, deptId:null}
	},
	methods: {
	    init : function() {
	        // 专业变更，获取该专业的题目 根据类型和等级分组.
	        $("#group", this.page).change(function() {
	            var groupId = $("#group", this.page).val();
	            if (groupId == "")
	                id = 0;
	            topic_index.getCountByType(groupId);
	        });
	        
	        $("input", "#mytable").each(function(i) {
	            $(this).attr("readonly", true);
	        });
	    },
		query: function () {
			vm.reload();
		},
		// 重载获取试卷列表.
		reloadPaperList: function (paperDesignId) {
            /*vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'roleName': vm.q.roleName},
                page:page
            }).trigger("reloadGrid");*/
            var page = $("#paperJqGrid").jqGrid('getGridParam','page');
            $("#paperJqGrid").jqGrid('setGridParam',{
                postData:{'paperDesignId': paperDesignId},
                page:page
            }).trigger("reloadGrid");
        },
		// 获取试卷列表.
		getPaperList : function () {
		    var id = getSelectedRow();
		    if(id == null){
                return;
            }
		    
		    if (getRowData(id).status != "已使用") {
                alert("只能查看已使用的试卷！");
                return;
            }
		    
		    vm.reloadPaperList(id);
		    
		    layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "试卷列表",
                area: ['500px', '500px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#paperList"),
                btn: ['取消']
            });
		},
		// 新增.
		add: function(){
		    vm.editType = "add";
			vm.showList = false;
			vm.addShow = true;
			vm.title = "新增";
			vm.paperDesign = {deptName:null, deptId:null};
			vm.getMajor(); // 获取专业
            vm.getTypeList(); // 获取题目类型list
            vm.getGradeList();// 获取题目等级list
            vm.initQuestions(); // 拼接
		},
		update: function (event) {
		    vm.editType = "update";
		    var id = getSelectedRow();
			if(id == null){
				return;
			}
			if (getRowData(id).status == "已使用") {
                alert("已生成试卷无法修改！");
                return;
            }
			vm.paperDesign = {deptName:null, deptId:null};
			vm.showList = false;
			vm.addShow = true;
            vm.title = "修改";
            
            vm.getInfo(id); // 获取数据.
            vm.getMajorForUpdate(); // 获取专业
            vm.getSectionListForUpdate(); // 获取章节.
            vm.getTypeList(); // 获取题目类型list
            vm.getGradeList();// 获取题目等级list
            vm.initQuestions(); // 拼接
            
            vm.getCountByType(true);
            // 回显题目数和分数.
            vm.getDetail();
		},
		
		//加载专业
		getMajor: function(event){
			$.ajax({
                type : 'get',
                async: false, // 同步.
                url : "/exam/major/getList",
                success : function(r) {
                    vm.majorList = r.majorList;
                    
                    $('#majorId').empty();
                    
                    $.each(vm.majorList, function(i, y) {
                        $('#majorId').append(
                                "<option value=" + y.id + ">"
                                        + y.majorName + "</option>");
                    });
                    
                    $('#majorId').selectpicker('refresh');
                    $('#majorId').selectpicker('val', '');
                }
            });
		},
		
		// 加载专业(修改时首次加载回显使用)
        getMajorForUpdate: function(event){
            $.ajax({
                type : 'get',
                async: false, // 同步.
                url : "/exam/major/getList",
                success : function(r) {
                    vm.majorList = r.majorList;
                    
                    $('#majorId').empty();
                    
                    var flag = false;
                    
                    var majorIds = vm.paperDesign.majorIds;
                    var majorIdArr = null;
                    if (majorIds != undefined && majorIds != null && majorIds != '') {
                        majorIdArr = majorIds.split(',');
                    }
                    $.each(vm.majorList, function(i, y) {
                            if (majorIdArr != null) {
                                for (var int = 0; int < majorIdArr.length; int++) {
                                    if(majorIdArr[int] == y.id){
                                        flag = true;
                                        break;
                                    }
                                }
                                if (flag){
                                    $('#majorId').append(
                                            "<option selected value=" + y.id + ">"
                                            + y.majorName + "</option>");
                                } else {
                                    $('#majorId').append(
                                            "<option value=" + y.id + ">"
                                            + y.majorName + "</option>");
                                }
                                flag = false;
                            } else {
                                $('#majorId').append(
                                        "<option value=" + y.id + ">"
                                        + y.majorName + "</option>");
                            }
                    });
                    
                    $('#majorId').selectpicker('refresh');
                }
            });
        },
		
		
		// 删除.
		del: function (event) {
		    //var ids = getSelectedRows();
		    var id = getSelectedRow();
		    if(id == null){
		        return ;
		    }
		    if (getRowData(id).status == "已使用") {
                alert("已生成试卷无法删除！");
                return;
            }
		    confirm('确定要删除选中的记录？', function(){
		        $.ajax({
		            type: "POST",
		            url: "/exam/paperDesign/remove/" + id,
		            success: function(r){
		                if(r.code == 0){
		                    alert('操作成功', function(index){
		                        $("#jqGrid").trigger("reloadGrid");
		                    });
		                }else{
		                    alert(r.msg);
		                }
		            }
		        });
		    });
		},
		
		// 生成试卷.
		produce: function (event) {
            var id = getSelectedRow();
            if(id == null){
                return ;
            }
            if (getRowData(id).status == "已使用") {
                alert("已生成试卷无法再次生成！");
                return;
            }
            confirm('是否确定要生成试卷，生成后该数据无法再次修改？', function(){
                $.ajax({
                    type: "POST",
                    url: "/exam/paperDesign/produce/" + id,
                    contentType: "application/json",
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        
        // 查看.
		getInfo: function(id){
		    $.ajax({
                type : 'post',
                async: false, // 同步.
                url : "/exam/paperDesign/find/"+id,
                success : function(r) {
                    vm.paperDesign = r.data;
                }
            });
		},
		
		// 题目类型，创建获取题目类型字典.
	    getTypeList: function() {
		    $.ajax({
                type : 'get',
                async: false, // 同步.
                url : '/exam/questionstype/getList',
                data: {
                    'disFlag' : 0
                },
                success : function(r) {
                    typeList = r.typeList;
                    for (var i = 0; i < typeList.length; i++) {
                        var item = typeList[i];
                        typeMap.set(item.id, item.questionTypeName);
                    }
                }
            });
	    },
	    
	    // 题目等级，创建获取题目等级字典.
	    getGradeList: function() {
	        $.ajax({
	            type : 'get',
	            async: false, // 同步.
	            data : {
	                'useState' : 0
	            },
	            url : '/exam/questionGrade/list',
	            success : function(r) {
	                gradeList = r.list;
	                for (var i = 0; i < gradeList.length; i++) {
	                    var item = gradeList[i];
	                    gradeMap.set(item.code, item.message);
	                }
	            }
	        });
	    },
	    
	    // 章节，根据专业获取.
	    getSectionList: function() {
	        var majorIds = $('#majorId').selectpicker('val');
	        //加载专业
            $.ajax({
                type : 'get',
                async: false, // 异步.
                //url : "/exam/section/selectByMajorId/" + majorId + "/0",
                url : "/exam/section/selectByMajorIdArr/" + majorIds,
                success : function(r) {
                    vm.sectionList = r.section;
                    
                    $('#sectionId').empty();
                    
                    $.each(vm.sectionList, function(i, y) {
                        $('#sectionId').append(
                                "<option value=" + y.id + ">"
                                        + y.majorName + "---" + y.sectionName + "</option>");
                    });
                    
                    
                    $('#sectionId').selectpicker('refresh');
                    $('#sectionId').selectpicker('val', '');
                }
            });
	    },
	    
        // 章节，根据专业获取.
        getSectionListForUpdate : function() {
            var majorIds = $('#majorId').selectpicker('val');
            //加载专业
            $.ajax({
                type : 'get',
                async: false, // 异步.
                url : "/exam/section/selectByMajorIdArr/" + majorIds,
                success : function(r) {
                    vm.sectionList = r.section;
                    
                    $('#sectionId').empty();
                    
                    $.each(vm.sectionList, function(i, y) {
                        
                        var sectionIds = vm.paperDesign.sectionIds;
                        if (sectionIds != undefined && sectionIds != null && sectionIds != '') {
                            var sectionIdArr = sectionIds.split(',');
                            for (var int = 0; int < sectionIdArr.length; int++) {
                                if(sectionIdArr[int] == y.id){
                                   flag = true;
                                   break;
                                }
                            }
                            if (flag){
                                $('#sectionId').append(
                                        "<option selected value=" + y.id + ">"
                                        + y.majorName + "---" + y.sectionName + "</option>");
                            } else {
                                $('#sectionId').append(
                                        "<option value=" + y.id + ">"
                                        + y.majorName + "---" + y.sectionName + "</option>");
                            }
                            flag = false;
                        }
                        
                        /*$('#sectionId').append(
                                "<option value=" + y.id + ">"
                                        + y.majorName + "---" + y.sectionName + "</option>");*/
                    });
                    
                    
                    $('#sectionId').selectpicker('refresh');
                }
            });
        },
	    
	    // 修改专业.
	    changeMajor : function() {
	        // 获取章节.
	        vm.getSectionList();
	        // 获取题目数量.
	        vm.getCountByType(true);
	    },
	    
	    
	    // 根据专业，获取题目数量（按照类型和等级分组）
	    getCountByType: function(isEdit) {
	        var majorIds = $('#majorId').selectpicker('val');
	        var sectionIds = $('#sectionId').selectpicker('val');
	        var url;
	        if (majorIds == undefined || majorIds == '' || majorIds == null) {
	            // 设置为0
	        } else if (sectionIds == undefined || sectionIds == '' || sectionIds == null) {
	            //url = '/exam/equestionmanagement/getCountByType/' + majorId;
	            url = '/exam/equestionmanagement/getCountByTypeMajorIds/' + majorIds;
	        } else {
	            //url = '/exam/equestionmanagement/getCountByType/' + majorId + '/' + sectionId;
	            url = '/exam/equestionmanagement/getCountByTypeMajorIdsAndSectionIds/' + majorIds + '/' + sectionIds;
	        }
	        
	        $.ajax({
                type : 'get',
                async: false, // 同步.
                url : url,
                success : function(r) {
                    if (isEdit == false) {
                        // 清空 题目总数
                        Vue.set(vm.paperDesign,'questionQuantity',0)
                        // 清空 题目总分.
                        Vue.set(vm.paperDesign,'totalScore',0)
                    }
                    
                    var list = r.list;
                    // disabled所有 题目数量input.
                    $("#mytable :input").attr("disabled", true);
                    // 清空所有 题目数量input.
                    $("#mytable :input").val("");
                    
                    if (list != null && list != undefined) {
                        for (var i = 0; i < list.length; i++) {
                            var questionsVO = list[i];
                            var typeId = questionsVO.typeId;
                            var grade = questionsVO.grade;
                            var totalCount = questionsVO.totalCount;
                            
                            $("#totalCount_" + typeId + "_" + grade).val(totalCount);
                            
                            $("#useCount_" + typeId + "_" + grade).attr("disabled", false);
                            $("#singleScore_" + typeId + "_" + grade).attr("disabled", false);
                            
                        }
                    }
                }
            });
	    },
	    
		// 初始化，题目数量和分数html.
	    initQuestions : function() {
	        var html = '';
	        // 循环题目类型.
	        for (var i = typeList.length - 1; i >= 0 ; i--) {
	            var typeO = typeList[i];
	            html += '<div class="panel panel-primary" style="float: left; width: 230px; margin: 3px;">'
	                + '<div class="panel-heading"><h3 class="panel-title">' + typeO.questionTypeName + '</h3></div>'
	                + '<div class="panel-body">'
	                + '<table style="width: 100%;">'
	                + '<tr>'
	                    + '<td></td><td><div style="margin: 3px;">选择数量</div></td><td><div style="margin: 3px;">题目数量</div></td><td><div style="margin: 3px;">每题分数</div></td>'
	                + '</tr>';
	                
	            // 循环题目等级.
	            for (var j = gradeList.length - 1; j >= 0 ; j--) {
	                var gradeO = gradeList[j];
	                html += '<tr>'  
	                    + '<td>' + gradeO.message + '</td>'
	                    // 选择数量.
	                    + '<td><div style="margin: 3px;">'
	                        + '<input class="form-control" style="width: 60px;" id="useCount_' + typeO.questionTypeNumber + '_' + gradeO.code + '" name="useCount_' + typeO.questionTypeNumber + '_' + gradeO.code + '"'
	                        + 'type="text" disabled="true" oninput="if(value.length > 3) value=value.slice(0, 3)"'
	                        + 'onkeyup="vm.setTotal(this.id, \'useCount_\')">'
	                    + '</div></td>'
	                    
	                    // 题目数量.
	                    + '<td><div style="margin: 3px;">'
	                        + '<input class="form-control" style="width: 60px;" id="totalCount_' + typeO.questionTypeNumber + '_' + gradeO.code + '" type="text" disabled="true">'
	                    + '</div></td>'
	                    
	                    // 每题分数.
	                    + '<td><div style="margin: 3px;">'
	                        + '<input class="form-control" style="width: 60px;" id="singleScore_' + typeO.questionTypeNumber + '_' + gradeO.code + '" name="singleScore_' + typeO.questionTypeNumber + '_' + gradeO.code + '" '
	                        + 'type="text" disabled="true"' 
	                        + 'oninput="if(value.length > 4) value=value.slice(0, 4)"'
	                        + 'onchange="vm.setTotal(this.id, \'singleScore_\')">'
	                        + '<input type="hidden"  id="singleTotalScore_' + typeO.questionTypeNumber + '_' + gradeO.code + '" name="singleTotalScore_' + typeO.questionTypeNumber + '_' + gradeO.code + '">' // 每种等级题目的分数，隐藏.
	                    + '</div></td>'
	                    + '</tr>'
	                
	            }
	                
	                    
	            html += '<tr>'
	                    + '<td>总分</td>'
	                    + '<td colspan="3"><div style="margin: 3px;">'
	                        + '<input class="form-control" style="width: 130px;" id="totalScore_' + typeO.questionTypeNumber + '" type="text" disabled="true">'
	                    + '</div></td>'
	                + '</tr>'
	                + '</table></div>'
	                + '</div>';
	        }
	        
	        $("#mytable").html(html);
	        
	    },
	    
	    // 校验.
	    check : function(id, type) {
	        if ("useCount_" == type) {
	            var typeGrade = id.split(type)[1];
	            // 选择数量.
	            var val1 = parseInt($("#" + id).val());
	            
	            if (typeof val1 !== 'number' || isNaN(val1)) {
	                $("#" + id).val("0");
	                return;
	            }
	            
	            
	            // 题目数量.
	            var val2 = parseInt($("#totalCount_" + typeGrade).val());
	            if ((val1) > (val2)) {
	                $("#" + id).val(val2);
	                return;
	            }
	            
	            $("#" + id).val(val1);
	            
	        } else if ("singleScore_" == type) {
	            
	            var val1 = $("#" + id).val();
	            
	            var objRegExp= /^(\d+)(\.\d+)?$/;
	            
	            if (!objRegExp.test($("#" + id).val()) || isNaN(val1)) {
	                $("#" + id).val("0");
	                return;
	                
	            }
	        }
	    },
	    
	    // 通过每题分数, 题目数量，设置总分.
	    setTotal : function(id, type) {
	        vm.check(id, type);
	        var typeGrade = id.split(type)[1];
	        var typeId = id.split("_")[1];
	        
	        if ("useCount_"== type) {
	            // 修改使用数量.
	            var singleScore = "singleScore_" + typeGrade;
	            var singleScoreV = $("#" + singleScore).val();
	            
	            // 计算当前类型题目总分.
	            if (singleScoreV != undefined && singleScoreV != '' && singleScoreV != null) {
	                var totalScore = "totalScore_" + typeId;
	                
	                // 当前类型，当前等级题目的总分数 = 每题分数*题目数量.
	                $("#singleTotalScore_" + typeGrade).val(vm.accAdd(vm.accMul(singleScoreV, $("#" + id).val())));
	                
	                
	                //  当前类型总分数 = 当前类型所有等级总分数
	                var totalScoreV = 0;
	                $("input[id^='singleTotalScore_" + typeId + "']").each(function() {
	                    if ($(this).val() != null && $(this).val() != undefined && $(this).val() != '') {
	                        totalScoreV = vm.accAdd(totalScoreV, $(this).val());
	                    }
	                })
	                $("#" + totalScore).val(totalScoreV);
	                
	            }
	            
	        } else if ("singleScore_"== type) {
	            // 修改每题分数.
	            var useCount = "useCount_" + typeGrade;
	            var useCountV = $("#" + useCount).val();
	            
	            // 计算当前类型题目总分.
	            if (useCountV != undefined && useCountV != '' && useCountV != null) {
	                var totalScore = "totalScore_" + typeId;
	                
	                // 当前题目类型，当前等级题目的总分数 = 每题分数*题目数量.
	                $("#singleTotalScore_" + typeGrade).val(vm.accAdd(vm.accMul($("#" + id).val(), useCountV)));
	                
	                
	                // 当前题目类型总分数 = 当前类型所有等级总分数
	                var totalScoreV = 0;
	                $("input[id^='singleTotalScore_" + typeId + "']").each(function() {
	                    if ($(this).val() != null && $(this).val() != undefined && $(this).val() != '') {
	                        totalScoreV = vm.accAdd(totalScoreV, $(this).val());
	                    }
	                })
	                $("#" + totalScore).val(totalScoreV);
	            }
	        } else {
	            return;
	        }
	        
	        // 题目总数.
	        var questionQuantity = 0;
	        $("input[id^='useCount_']").each(function() {
	            if ($(this).val() != null && $(this).val() != undefined && $(this).val() != '') {
	                questionQuantity = vm.accAdd(questionQuantity, $(this).val());
	            }
	        })
	        Vue.set(vm.paperDesign,'questionQuantity',questionQuantity)
	        // 题目总分.
	        var totalScore = 0;
	        $("input[id^='totalScore_']").each(function() {
	            if ($(this).val() != null && $(this).val() != undefined && $(this).val() != '') {
	                totalScore = vm.accAdd(totalScore, $(this).val());
	            }
	        })
	        Vue.set(vm.paperDesign,'totalScore',totalScore)
	        
	    },
	    
	    // 题目等级，创建获取题目等级字典.
	    getDetail : function() {
	        var id = vm.paperDesign.id;
	        $.ajax({
	            type : 'get',
	            async: false, // 同步.
	            data : {
	                'id' : id
	            },
	            url : '/exam/paperDesign/getDetail',
	            success : function(list) {
	                for (var i = 0; i < list.length; i++) {
	                    var item = list[i];
	                    var typeId = item.questionTypeId;
	                    var grade = item.questionGrade;
	                    var useCount = item.useCount;
	                    var singleScore = item.singleScore;
	                    var singleTotalScore = item.singleTotalScore;
	                    
	                    $("#useCount" + "_" + typeId + "_" + grade).val(useCount);
	                    $("#singleScore" + "_" + typeId + "_" + grade).val(singleScore);
	                    $("#singleTotalScore" + "_" + typeId + "_" + grade).val(singleTotalScore);
	                }
	                
	                for (var i = typeList.length - 1; i >= 0 ; i--) {
	                    // 当前题目类型总分数 = 当前类型所有等级总分数.
	                    var totalScoreV = 0;
	                    // 题目类型编号.
	                    var questionTypeNumber = typeList[i].questionTypeNumber;
	                    $("input[id^='singleTotalScore_" + questionTypeNumber + "']").each(function() {
	                        if ($(this).val() != null && $(this).val() != undefined && $(this).val() != '') {
	                            totalScoreV = vm.accAdd(totalScoreV, $(this).val());
	                        }
	                    })
	                    if (totalScoreV != 0) {
	                        $("#totalScore_" + questionTypeNumber).val(totalScoreV);
	                    }
	                }
	            }
	        });
	    },
	    
	    // 保存或者修改.
	    saveOrUpdate : function() {
            if (vm.paperDesign.majorIds == "0") {
                alert("请选择专业");
            } else if (vm.paperDesign.name == "") {
                alert("请输入试卷名称");
            } else if (vm.paperDesign.produceQuantity == "" || vm.paperDesign.produceQuantity < 0) {
                alert("请输入正确的试卷数量");
            } else if (vm.paperDesign.produceQuantity > 10 ) {
                alert("试卷数量最多为10，请修改！");
            } else {
                $form = $("#paperProduceform");
                if (vm.editType == "add") {
                    var url = "/exam/paperDesign/add";
                } else if (vm.editType == "update") {
                    url = "/exam/paperDesign/edit";
                }
                
                $("#majorIds").val($('#majorId').selectpicker('val'));
                if ($('#sectionId').selectpicker('val') != undefined && $('#sectionId').selectpicker('val') != null && $('#sectionId').selectpicker('val') != '') {
                    $("#sectionIds").val($('#sectionId').selectpicker('val'));
                }
                $.post(url, $form.serialize(), function(res) {
                    if (res.code == 0) {
                        alert("成功");
                        vm.reload();
                    } else {
                        alert(res.message);
                    }
                }, 'json');
            }
        },
        
	    // 返回.
		reload: function (event) {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
				postData:{'username': vm.q.username},
                page:page
            }).trigger("reloadGrid");
		},
		
		/*---------------js 两个数加 ------------------------------*/
		accAdd : function(arg1, arg2) {
		    if (arg1 == '' || arg1 == null || arg1 == undefined) {
		        arg1 = 0;
		    }
		    if (arg2 == '' || arg2 == null || arg2 == undefined) {
		        arg2 = 0;
		    }
		    var r1 = 0, r2 = 0, m;
		    try {r1 = arg1.toString().split(".")[1].length;} catch(e) {}
		    try {r2 = arg2.toString().split(".")[1].length;} catch(e) {}
		    // 相加，小数位数为两个数中小数最长的.
		    m=Math.pow(10,Math.max(r1,r2));
		    return (arg1*m+arg2*m)/m;
		},
		/*---------------js 两个数相乘 ------------------------------*/
		accMul : function(num1, num2) {
		    if (num1 == '' || num1 == null || num1 == undefined) {
		        num1 = 0;
		    }
		    if (num2 == '' || num2 == null || num2 == undefined) {
		        num2 = 0;
		    }
		    var m = 0;
		    var n = 0;
		    var s1 = num1.toString();
		    var s2 = num2.toString();
		    // 相乘，小数位数为两个数小数之和.
		    try { m = s1.split(".")[1].length; } catch (e) {};
		    try { n = s2.split(".")[1].length; } catch (e) {};
		    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m+n);
		}
	}
});

//下载pdf.
function downLoadPaper(id, paperName) {
    location.href= baseURL +"exam/paperProduce/download?produceId=" + id + "&paperName=" + paperName;
}

// 查看试卷.
function seePaper (paperId, paperName) {
    $.ajax({
        type : 'post',
        data : {produceId : paperId},
        url : "/exam/paperProduce/getQuestionInfo",
        success : function(r) {
            var paperInfoHtml = '<ul>';
            // 循环题目.
            $.each(r.questionList, function(i,y) {
                paperInfoHtml += i + 1 + ". [" + y.typeName + "] " + y.content + "(" + y.score + "分)" + "<br/>";
                
                // 循环选项.
                $.each(y.optionList, function(j,z) {
                    paperInfoHtml += z.flag + "." + z.content+ "<br/>";
                })
                paperInfoHtml += "<br/>";
                
            })
            paperInfoHtml += '<br/><br/><br/><br/><br/>';
            paperInfoHtml +=  '答案<br/>' + r.answer;
            paperInfoHtml += '</ul>';
          $("#paperInfo").html(paperInfoHtml);
          
          
          layer.open({
              type: 1,
              offset: '50px',
              skin: 'layui-layer-molv',
              title: "试卷查看--" + paperName,
              area: ['700px', '700px'],
              shade: 0,
              shadeClose: false,
              content: jQuery("#paperInfo"),
              btn: ['取消']
          });
        }
    });
}

// 时间格式化.
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "H+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

